package com.leo.foodmaster.ureport2.config;

import com.bstek.ureport.console.UReportServlet;
import com.bstek.ureport.definition.datasource.BuildinDatasource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>
 * ureport2配置类
 * </p>
 *
 * @author ：Leo
 * @since ：2021/9/22 11:05
 */
@Configuration
@ImportResource("classpath:ureport-console-context.xml")
public class Ureport2Config implements BuildinDatasource {
    @Resource
    private DataSource dataSource;

    @Value("${ureport.fileStoreDir}")
    private String fileStoreDir;

    @Value("${ureport.disableFileProvider}")
    private boolean disabled;


    /**
     * 进行注册Servlet
     * 配置 UReport2 需要使用到的servlet
     */
    @Bean
    public ServletRegistrationBean<UReportServlet> buildUReportServlet() {
        // urlMappings 值为“/ureport/*”的 urlMappings 是一定不能变的，否则系统将无法运行。
        return new ServletRegistrationBean<>(new UReportServlet(), "/ureport/*");
    }


    @Bean
    public CustomFileReportProvider customFileReportProvider() {
        CustomFileReportProvider customFileReportProvider = null;
        if (disabled) {
            customFileReportProvider = new CustomFileReportProvider();
            customFileReportProvider.setDisabled(!disabled);
            customFileReportProvider.setFileStoreDir(fileStoreDir);
        }
        return customFileReportProvider;
    }


    @Override
    public String name() {
        return "ureport2数据源";
    }

    @Override
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("获取ureport2数据源出错了");
            e.printStackTrace();
        }
        return null;
    }
}
